<template>
    <div class="container">
        <!-- 面包屑导航 -->
        <div class="topNav">
            <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
                <el-breadcrumb-item>成本调整单</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <!-- 编辑/新增 成本调整单操作区域 -->
        <div class="together-content">
            <!-- 成本调整表单 -->
            <div>
                <el-form :inline="true" label-width="auto" style="width: 100%;">
                    <!-- 单据编号 -->
                    <el-form-item label="单据编号:" v-show="costAdjustOrder.code">
                        <span v-show="costAdjustOrder.status >= 2">{{ costAdjustOrder.code }}</span>
                        <el-input v-show="costAdjustOrder.status < 2" v-model="costAdjustOrder.code"
                            style="width: 150px;" readonly />
                    </el-form-item>

                    <!-- 单据日期 -->
                    <el-form-item label="单据日期:">
                        <span v-if="costAdjustOrder.status >= 2">{{ costAdjustOrder.createdTime }}</span>
                        <el-date-picker v-else-if="costAdjustOrder.status < 2" v-model="costAdjustOrder.createdTime"
                            type="date" placeholder="选择日期" size="small" style="width: 150px"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>

                    <!-- 上传附件 -->
                    <el-form-item v-show="costAdjustOrder.status < 2">
                        <el-link type="primary" style="margin-left: 20px; height: 1.2rem">
                            <el-icon>
                                <Link />
                            </el-icon>上传附件
                        </el-link>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 分割线 -->
            <el-divider />

            <!-- 操作按钮 -->
            <div style="margin-bottom: 15px; text-align: right">
                <el-button type="primary" size="small" @click="save" v-show="costAdjustOrder.status < 2" >保存</el-button>
                <el-button type="success" size="small" @click="saveAndSubmit" v-show="costAdjustOrder.status < 2" >保存并提交</el-button>
                <el-button type="success" size="small" v-show="costAdjustOrder.status == 2"
                    @click="auditor">审核</el-button>
                <el-button type="info" size="small" v-show="costAdjustOrder.status == 3" >反审核</el-button>
            </div>

            <!-- 成本调整明细 -->
            <el-table :data="detailList" style="width: 100%" border>
                <!-- 操作列 -->
                <el-table-column v-if="costAdjustOrder.status < 2" label="操作" width="80px" align="center" fixed="left">
                    <template #default="scope">
                        <el-button link type="success" size="small" plain @click="addDetailRow(scope.$index)">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-button>
                        <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)">
                            <el-icon>
                                <Minus />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>

                <!-- 商品 -->
                <el-table-column label="商品" width="200px" align="center">
                    <template #default="scope">
                        <span v-show="costAdjustOrder.status >= 2">{{ scope.row.goodsName }}</span>
                        <el-input v-show="costAdjustOrder.status < 2" v-model="scope.row.goodsName" size="small"
                            style="width: 95%" placeholder="选择商品" @click="openGoodsDialog(scope.row, scope.$index)"
                            readonly />
                    </template>
                </el-table-column>

                <!-- 单位 -->
                <el-table-column label="单位" width="150px" align="center">
                    <template #default="scope">
                        <span v-show="costAdjustOrder.status >= 2">{{ scope.row.unitName }}</span>
                        <el-select v-show="costAdjustOrder.status < 2" v-model="scope.row.unitName" size="small"
                            style="width: 95%" :disabled="!scope.row.goodsId">
                            <el-option v-for="unit in units" :key="unit.id" :label="unit.name" :value="unit.name" />
                        </el-select>
                    </template>
                </el-table-column>

                <!-- 仓库库存数量 -->
                <el-table-column label="库存数量" width="150px" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.availableStock }}</span>
                    </template>
                </el-table-column>

                <!-- 原成本 -->
                <el-table-column label="原单位成本" width="150px" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.cost }}</span>
                    </template>
                </el-table-column>

                <!-- 调整金额 -->
                <el-table-column label="*调整金额" width="150px" align="center">
                    <template #default="scope">
                        <span v-show="costAdjustOrder.status >= 2">{{ scope.row.adjustmentPrice }}</span>
                        <el-input-number v-show="costAdjustOrder.status < 2" v-model.number="scope.row.adjustmentPrice"
                            size="small" style="width: 95%" :min="0" :max="99999999.99" step="1" />
                    </template>
                </el-table-column>

                <!-- 原成本 -->
                <el-table-column label="计算单位成本" width="150px" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.adjustedCost }}</span>
                    </template>
                </el-table-column>

                <!-- 仓库 -->
                <el-table-column label="*仓库" width="200px" align="center">
                    <template #default="scope">
                        <span v-show="costAdjustOrder.status >= 2">{{ scope.row.warehouseName }}</span>
                        <el-input v-show="costAdjustOrder.status < 2" v-model="scope.row.warehouseName" readonly
                            size="small" placeholder="选择仓库" @click="openWarehouseDialog(scope.row, scope.$index)"
                            style="width: 95%" />
                    </template>
                </el-table-column>


                <!-- 备注 -->
                <el-table-column label="备注" width="200px" align="center">
                    <template #default="scope">
                        <span v-show="costAdjustOrder.status >= 2">{{ scope.row.remark }}</span>
                        <el-input v-show="costAdjustOrder.status < 2" v-model="scope.row.remark" size="small"
                            style="width: 95%" placeholder="备注" />
                    </template>
                </el-table-column>
            </el-table>

            <!-- 合计行 -->
            <div style="background-color: #fffbe6; padding: 10px; margin-top: 10px; border: 1px solid #f0f0f0;">
                <strong>合计：</strong>
                <span style="margin-left: 20px;">{{ totalAmount.toFixed(2) }}</span>
            </div>

            <!-- 备注 -->
            <div v-show="costAdjustOrder.status >= 2">
                <p><strong>备注：</strong><span>{{ costAdjustOrder.remark || '暂无备注信息' }}</span></p>
            </div>
            <el-input v-show="costAdjustOrder.status < 2" v-model="costAdjustOrder.remark" style="width: 100%"
                type="textarea" placeholder="暂无备注信息" />

            <!-- 操作日志 & 历史记录 -->
            <div style="margin-bottom: 15px; text-align: right">
                <br />
                <el-button plain @click="router.push({ name: 'cost' })">历史记录</el-button>
                <el-button plain>操作日志</el-button>
            </div>

            <!-- 弹窗 -->
            <template v-if="costAdjustOrder.status < 2">
                <!-- 仓库搜索弹窗 -->
                <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" draggable :show-close="true">
                    <WareHouse ref="warehouseRef"
                        :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
                    <br /><br />
                </el-dialog>

                <!-- 商品搜索弹窗 -->
                <el-dialog v-model="goodsVisible" title="商品搜索列表" width="70%" draggable :show-close="true">
                    <FreeGoodsSelect v-model="goodsVisible" @confirm="onGoodsSelected"></FreeGoodsSelect>
                    <br /><br />
                </el-dialog>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, defineProps, onMounted, inject } from "vue";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {formatDate} from '@/util'
import WareHouse from '@/views/basic/WareHouse.vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";

const router = useRouter();
const axios = inject("axios");

// 数据定义
const costAdjustOrder = ref({
    id: '',
    code: '',
    createdTime: formatDate(new Date()),
    companyId: '', // 假设从用户获取
    remark: '',
    status: 0
});

const detailList = ref(null);
const totalAmount = ref(0);

// 弹窗控制
const warehouseVisible = ref(false);
const goodsVisible = ref(false);
const currentRow = ref(null), currentIndex = ref(null);

// 计算合计
watch(detailList, () => {
  const list = detailList.value || []; // 如果是 null/undefined，转为空数组
  totalAmount.value = list.reduce((sum, item) => {
    return sum + (item?.adjustmentPrice ?? 0);
  }, 0);
}, { deep: true });

let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
            //获取到仓库编码，存数据库用，仓库name仅用作展示
            currentRow.value.warehouseId = warehouseRef.value.selectedArray[0].id;
            currentRow.value.warehouseName = warehouseRef.value.selectedArray[0].name;
            //用完之后清空，避免污染其他地方数据
            warehouseRef.value.clearSelected();
        }
    }
})

// 商品选择弹窗
function openGoodsDialog(row, index) {
    goodsVisible.value = true;
    currentRow.value = row;
    currentIndex.value = index;
}

// 仓库选择弹窗
function openWarehouseDialog(row, index) {
    warehouseVisible.value = true;
    currentRow.value = row;
    currentIndex.value = index;
}

// 商品选择回调
const onGoodsSelected = (selected) => {
    if (selected.length > 0) {
        //当前行后面添加选中的的商品信息
        let arr = [];
        for (let i = 0; i < selected.length; i++) {
            let obj = {
                goodsId: selected[i].id,
                goodsCode: selected[i].code,
                goodsName: selected[i].code + ' ' + selected[i].name,
                unitId: selected[i].unitId || null,
                unitName: selected[i].unitName || null,
                availableStock: selected[i].availableStock || null,
                warehouseId: selected[i].warehouseId || null,
                warehouseName: selected[i].warehouseName || null,
                batchNo: selected[i].type == 1 ? selected[i].batchNo : null,
                cost: selected[i].cost || 0
            }
            arr[i] = obj
        }
        console.log("arr", arr);
        //当前下标往后添加选中的商品
        detailList.value.splice(currentIndex.value, 1, ...arr);
        console.log("onGoodsSelected", selected)
    }
};

// 添加行
const addDetailRow = (index) => {
    detailList.value.splice(index + 1, 0, {});
};

// 删除行
const removeDetailRow = (index) => {
    if (detailList.value.length === 1) {
        ElMessage({ message: '至少保留一条记录', type: 'warning' });
        return;
    }
    detailList.value.splice(index, 1);
};



// 新增前的校验
let filteredDetailList = ref(null);
const validSave = () => {
    // 过滤掉 goods 为空的明细项
    filteredDetailList.value = detailList.value.filter(item => {
        return item.goodsId && item.goodsName;
    });

    // 校验：至少有一条有效明细
    if (!filteredDetailList.value || filteredDetailList.value.length === 0) {
        ElMessage({ message: '请添加要调整的商品', type: 'warning' });
        return false;
    }

    // 用于记录已出现的 "仓库ID + 商品ID" 组合
    const seenWarehouseGoods = new Set();

    for (let i = 0; i < filteredDetailList.value.length; i++) {
        const detail = filteredDetailList.value[i];

        // 校验仓库是否选择
        if (!detail.warehouseId) {
            ElMessage({ message: `请选择【${detail.goodsName}】的仓库`, type: 'warning' });
            return false;
        }

        // 校验调整金额（注意：你原代码写的是 adjustmentPrice，但字段应为 adjustmentPrice？）
        // 假设你想校验的是 adjustmentPrice > 0
        if (detail.adjustmentPrice == null || detail.adjustmentPrice <= 0) {
            ElMessage({ message: `商品【${detail.goodsName}】的调整单价必须大于0`, type: 'warning' });
            return false;
        }

        // 构建唯一键：仓库 + 商品
        const key = `${detail.warehouseId}-${detail.goodsId}`;

        // 检查是否重复
        if (seenWarehouseGoods.has(key)) {
            ElMessage({
                message: `商品【${detail.goodsName}】在仓库【${detail.warehouseName}】中已存在，不能重复添加`,
                type: 'warning'
            });
            return false;
        }

        // 记录该组合
        seenWarehouseGoods.add(key);
    }

    return true;
};




// 保存
const save = () => {
    if (props.id) { //修改
        if(validSave()) {
            modify();
        }
    } else { //新增
        if (validSave()) {
            // 发送请求
            add();
        }
    }

};

const saveAndSubmit = () => {
    costAdjustOrder.value.status = 2;
    save();
};

// 修改
let originalDetailList = ref(null), originalOrder = ref(null);
const modify = async () => {
  //1.map根据id快速获取原数组
  const originalMap = new Map(
    originalDetailList.value.map(item => [item.id, item])
  );
  //2.遍历当前列表：找新增 & 修改
  let addList = [], delList = [], modList = [];
  filteredDetailList.value.forEach(i => {
    if (!i.id) {
      addList.push(i); //新增
    } else {
      if (hasModifiedDetail(i, originalMap.get(i.id))) {
        modList.push(i);
      }
      //map数据比较过就删除， map中数据 - 当前明细 = 已删除数据
      originalMap.delete(i.id);
    }
  })
  //3.剩下的 originalMap 中的 id 就是被删除的
  for (const id of originalMap.keys()) {
    delList.push(id);
  }
  //提交修改
  try {
    const rs = await axios({
      url: `/xyy/costAdjustment/modify`,
      method: 'post',
      data: {
        orderModified: hasModifiedOrder(originalOrder.value, costAdjustOrder.value),
        addList: addList,
        modList: modList,
        delList: delList,
        costAdjustment: costAdjustOrder.value
      }
    })
    if (rs.data.code == 5200) {
      ElMessage({ message: "修改成本调整单成功", type: 'success', });
      router.push({ name: 'cost' });
      return;
    }
    ElMessage({ message: "修改成本调整单失败", type: 'danger', });
  } catch (error) {
    console.log(error);
    ElMessage({ message: `修改成本调整单异常:${error.message}`, type: 'danger', });
  }

}
//判断当前 调拨明细 是否修改
function hasModifiedDetail(current, original) { //判断这个商品是否修改的前提：商品id或code存在，其他：商品单位、仓库、批次号、库位、数量、单价修改即表示该明细修改了
  const fields = ["unitId", "warehouseId", "goodsId", "adjustmentPrice", "remark"];
  return fields.some(field => current[field] != original[field]);
}
//判断当前 调拨单 是否修改
function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "remark", "status"]
  return fields.some(field => current[field] != original[field]);
}

// 新增
const add = async () => {
  try {
    const rs = await axios({
      url: '/xyy/costAdjustment/create', method: 'post',
      data: {
        costAdjustment: costAdjustOrder.value,
        costAdjustmentDetailList: filteredDetailList.value
      }
    })
    if (rs.data.code == 5200) {
      ElMessage({ message: '新增成本调整单成功！', type: 'success' })
      router.push({ name: 'cost' });
      return;
    } else {
      ElMessage({ message: '新增成本调整单失败！', type: 'danger' })
    }
  } catch (error) {
    ElMessage({ message: error.message, type: 'danger' })
  }
}



const auditor = () => {
    ElMessage({ message: '审核成功', type: 'success' });
};

// 初始化
const props = defineProps(['id']);

onMounted(() => {
    if (props.id) {
        init();
    }else {
        detailList.value = [{}]
    }
});

const init = async () => {
  try {
    const rs = await axios({
      url: `/xyy/costAdjustment/get/${props.id}`,
      method: 'post',
    })

    if (rs.data.code == 5200) {
      costAdjustOrder.value = rs.data.costAdjustRequest.costAdjustment;
      detailList.value = rs.data.costAdjustRequest.costAdjustmentDetailList;
      //深拷贝一份初始数据，方便后面操作
      originalOrder.value = JSON.parse(JSON.stringify(rs.data.costAdjustRequest.costAdjustment));
      originalDetailList.value = JSON.parse(JSON.stringify(rs.data.costAdjustRequest.costAdjustmentDetailList));
      return;
    }
    ElMessage({ message: '', type: 'danger' })

  } catch (error) {
    console.log(error);
  }

}

</script>